<template>
  <view class="c-pd" v-if="data.info">
    <view class="mb-3 bg-white c-br">
      <van-cell-group inset>
        <van-grid :border="false" column-num="2">
          <van-grid-item :icon="item.iconName" :text="item.name" v-for="(item, index) in data.menuList" :key="index" @click="menuChange(item.id)" />
        </van-grid>
      </van-cell-group>
    </view>
    <view class="mb-3">
      <van-cell-group inset>
        <van-cell :border="false" use-label-slot>
          <view slot="title" class="c-text-16 font-bold"> 通知信息 </view>
        </van-cell>
        <van-cell-group>
          <van-cell title="事故发生地" :value="data.info.address || '未知地址'" />
          <van-cell title="事故类型" :value="data.info.typeName || '未知类型'" />
          <van-cell title="发生时间" :value="data.info.createDate || '未知时间'" />
        </van-cell-group>
      </van-cell-group>
    </view>
    <view class="mb-3">
      <van-cell-group inset>
        <van-cell :border="false" use-label-slot>
          <view slot="title" class="c-text-16 font-bold"> 通知统计 </view>
        </van-cell>
        <van-grid>
          <van-grid-item use-slot v-for="(item, index) in data.statisticsList" :key="index">
            <view>{{ item.name }}</view>
            <view>{{ item.value }}</view>
          </van-grid-item>
        </van-grid>
      </van-cell-group>
    </view>
    <view class="mb-3">
      <van-cell-group inset>
        <van-cell :border="false" use-label-slot>
          <view slot="title" class="c-text-16 font-bold"> 通知明细 </view>
          <view slot="right-icon" @click="getMx">
            <i class="i-ix:reload"></i>
          </view>
        </van-cell>
        <van-cell-group>
          <van-cell center use-label-slot v-for="(item, index) in data.info.taskRecordList" :key="index">
            <view slot="title">
              <van-tag type="primary" v-if="item.notifyState === 1">通知中</van-tag>
              <van-tag type="success" v-if="item.notifyState === 10">通知成功</van-tag>
              <van-tag type="danger" v-if="item.notifyState === -1">通知失败</van-tag>
            </view>
            <view slot="right-icon">
              <van-button color="#ffc300" v-if="item.notifyState === -1" class="mr-2" @click="noticeClick(item.taskRecordId)" size="mini">我已通知</van-button>
              <i class="i-solar:phone-linear c-text-16" @click="phoneFilter(item.phones)"></i>
            </view>
            <view slot="label" class="flex items-center">
              <view class="w-5%">
                <i class="i-basil:location-outline c-text-12"></i>
              </view>
              <view class="w-95%">
                <text>{{ item.address }}</text>
              </view>
            </view>
          </van-cell>
        </van-cell-group>
      </van-cell-group>
    </view>
    <van-action-sheet
      :close-on-click-overlay="true"
      @click-overlay="
        () => {
          data.phoneShow = false;
        }
      "
      @select="
        (e: any) => {
          Tools.callPhone(String(e.detail.name));
        }
      "
      :show="data.phoneShow"
      :actions="data.phoneList"
    />
  </view>
</template>

<script setup lang="ts">
import useToast from '@/hooks/useToast';
import useModal from '@/hooks/useModal';
import { navigate } from '@/utils/navigate';
import HomeRequest from '@/request/homeRequest';
import { EAlarmType } from '@/enum/index';
import Tools from '@/utils/tools';
import useAppStore from '@/store/modules/app';

interface IMenuList {
  id: number;
  name: string;
  iconName: string;
}

interface ICardList {
  label: string;
}

interface IStatistics {
  name: string;
  value: number;
}

interface IData {
  menuList: IMenuList[];
  cardList: ICardList[];
  info?: IGetNotifyDetail;
  statisticsList: IStatistics[];
  phoneList: { name: string }[];
  beeperId: number;
  notifyId?: number;
  phoneShow: boolean;
}

const store = useAppStore();

const data = reactive<IData>({
  menuList: [
    {
      iconName: 'orders-o',
      name: '通知列表',
      id: 1,
    },
    {
      iconName: 'phone-o',
      name: '一键重播',
      id: 2,
    },
  ],
  cardList: [],
  statisticsList: [],
  phoneList: [],
  beeperId: store.$state.beeperId,
  phoneShow: false,
});

const { showToast } = useToast();

const { showModal } = useModal();

onLoad((options) => {
  if (options !== undefined && options !== null) {
    data.notifyId = options.notifyId || 0;
    if (data.notifyId) {
      data.menuList.splice(0, 1);
    }
  }
  getNotifyDetails();
});

//获取通知统计
const getStatisticsList = (notifyId: number) => {
  HomeRequest.GetNotifyStatistics({ notifyId }).then((res) => {
    const datas = res.data;
    const keyOrder: Array<keyof typeof datas> = ['sumHouse', 'successHouse', 'notifyPhone', 'connectedPhone'];
    const dataArray = keyOrder.map((key) => {
      let name;
      switch (key) {
        case 'sumHouse':
          name = '通知户数';
          break;
        case 'successHouse':
          name = '成功户数';
          break;
        case 'notifyPhone':
          name = '通知人数';
          break;
        case 'connectedPhone':
          name = '接通人数';
          break;
        default:
          name = 'Unknown';
      }
      return {
        name,
        value: datas[key],
      };
    });
    data.statisticsList = dataArray;
  });
};

//更新明细
const getMx = () => {
  HomeRequest.GetMxList({ notifyId: data.info!.notifyId, hasLoading: true }).then((res) => {
    showToast('更新成功');
    data.info!.taskRecordList = res.data;
    getStatisticsList(data.info!.notifyId);
  });
};

//获取通知详情
const getNotifyDetails = () => {
  let params: any = { beeperId: data.beeperId, hasLoading: true };
  if (data.notifyId) {
    delete params.beeperId;
    HomeRequest.GetNotifyDetailId({ notifyId: data.notifyId, ...params }).then((res) => {
      data.info = res.data;
      data.info.typeName = EAlarmType[data.info.notifyType as keyof typeof EAlarmType];
      getStatisticsList(data.info!.notifyId);
    });
  } else {
    HomeRequest.GetNotifyDetail(params).then((res) => {
      data.info = res.data;
      data.notifyId = res.data.notifyId;
      data.info.typeName = EAlarmType[data.info.notifyType as keyof typeof EAlarmType];
      getStatisticsList(data.info.notifyId);
    });
  }
};

//通知详情操作
const menuChange = (id: number) => {
  switch (id) {
    case 1:
      navigate({ url: '/subcontract/home/notifyDetail/list' });
      break;
    case 2:
      HomeRequest.OnekeyReport({ notifyId: data.info!.notifyId }).then((res) => {
        if (res.data === null) {
          showToast('操作成功');
          setTimeout(() => {
            getNotifyDetails();
          }, 1000);
        }
      });
      break;
  }
};

//号码过滤
const phoneFilter = (phones: string) => {
  if (!phones) {
    showToast('暂无可拨打的号码');
    return;
  }
  if (phones.includes(',')) {
    data.phoneList = phones.split(',').map((item) => {
      return { name: item }; // 每个选项对象都设置 name 为 '选项'
    });
  } else {
    data.phoneList = [{ name: phones }];
  }
  data.phoneShow = true;
};

//确认通知
const noticeClick = (taskRecordId: number) => {
  showModal('是否确定已通知？', {
    success: (resM) => {
      if (resM.confirm) {
        HomeRequest.OfflineNotice({
          taskRecordId: taskRecordId,
          hasLoading: true,
        }).then((res) => {
          if (res.status === 0) {
            showToast('操作成功');
            getNotifyDetails();
            getMx();
          }
        });
      }
    },
  });
};
</script>
